<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2018/11/13
 * Time: 13:59
 */

namespace frontend\modules\resource\logic;

use common\models\BranchResource;

use common\models\HyResource;
use common\models\HySpecialResource;
use common\models\HySupport;
use frontend\modules\common\models\BaseHelper;
use Yii;
use yii\db\Exception;


class BranchResourceLogic
{
    /**
     * @param $id
     * @param $type
     * @param $r_type
     * @param $branchId
     * @return int
     * @throws \yii\base\ExitException
     * @throws \yii\db\Exception
     */
    public function AddSupport($id, $type, $r_type, $branchId)
    {
        $data = $this->CheckParam($id, $r_type, $branchId);

        $sql = "INSERT IGNORE INTO `hy_support` (`res_id`, `res_title`,`res_type`,`sup_type`,`br_id`,`created_at`) VALUES ";
        $str = '';
        foreach ($data as $key => $val) {
            $str .= '(' . $val['res_id'] . ',\'' . $val['res_title'] . '\',' . $val['type'] . ',' . $type . ',' . $val['br_id'] . ',\'' . date('Y-m-d H:i:s') . '\')' . ',';
        };
        $sql .= trim($str, ',');
        $res = Yii::$app->db->createCommand($sql)->execute();
        return $res;
    }

    /**
     * @param $id
     * @param $spId
     * @param $r_type
     * @param $branchId
     * @return int
     * @throws \yii\base\ExitException
     * @throws \yii\db\Exception
     */
    public function AddSpecialResource($id, $spId, $r_type, $branchId)
    {
        $data = $this->CheckParam($id, $r_type, $branchId);

        $sql = "INSERT IGNORE INTO `hy_special_resource` (`res_id`, `res_title`,`type`,`br_id`,`sp_id`,`created_at`) VALUES ";
        $str = '';
        foreach ($data as $key => $val) {
            $str .= '(' . $val['res_id'] . ',\'' . $val['res_title'] . '\',' . $val['type'] . ',' . $val['br_id'] . ',' . $spId . ',\'' . date('Y-m-d H:i:s') . '\')' . ',';
        };
        $sql .= trim($str, ',');
        $res = Yii::$app->db->createCommand($sql)->execute();
        return $res;
    }


    /**
     * 校验参数 是否合法
     * @param $id
     * @param $r_type
     * @param $branchId
     * @return array|\yii\db\ActiveRecord[]
     * @throws \yii\base\ExitException
     */
    public function CheckParam($id, $r_type, $branchId, $need = 'data')
    {
        if (empty($id))
            BaseHelper::Error('id 不能为空');

        $res_id = $this->_getRes_id($id, $r_type);

        $data = (new BranchResource())->find()
            ->select(['res_id', 'res_title', 'type', 'br_id'])
            ->where(['res_id' => $res_id])
            ->andWhere(['br_id' => $branchId])
            ->asArray()
            ->all();
        if (empty($data))
            BaseHelper::Error('没有找到该店铺的对应资源');

        return $$need;
    }

    /**
     * @param $id
     * @param $r_type
     * @throws \yii\base\ExitException
     */
    private function _getRes_id($id, $r_type)
    {

        $model = (new ResourceLogic())->getResourceModel($r_type);
        $res = $model->find()
            ->select('res_id')
            ->where(['id' => $id])
            ->indexBy('res_id')
            ->asArray()
            ->all();

        if (empty($res))
            BaseHelper::Error('没有找到对应资源');
        return array_keys($res);

    }

    /**
     * 从分馆移除资源
     * @param $id
     * @param $r_type
     * @param $branchId
     * @return int
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    public function RemoveBranchResource($id, $r_type, $branchId)
    {
        $res_id = $this->CheckParam($id, $r_type, $branchId, 'res_id');

        $transaction = Yii::$app->db->beginTransaction();
        try {
            //从关联表移除
            $res = BranchResource::deleteAll(['res_id' => $res_id, 'br_id' => $branchId]);
            $this->RemoveThird($res_id, $branchId);
            $transaction->commit();
            return $res;
        } catch (Exception $e) {
            $transaction->rollBack();
            BaseHelper::Error($e->getMessage());
        }
    }

    /**
     * 分馆删除资源
     * @param $id
     * @param $r_type
     * @param $branchId
     * @return int
     * @throws Exception
     * @throws \yii\base\ExitException
     */
    public function DeleteBranchResource($id, $r_type, $branchId)
    {
        $res_id = $this->CheckParam($id, $r_type, $branchId, 'res_id');

        $transaction = Yii::$app->db->beginTransaction();
        try {
            //从关联表移除
            $res = BranchResource::updateAll(['status' => 0], ['res_id' => $res_id, 'br_id' => $branchId]);
            HyResource::deleteAll(['id' => $res_id]);
            $this->RemoveThird($res_id, $branchId);
            $transaction->commit();
            return $res;
        } catch (Exception $e) {
            $transaction->rollBack();
            BaseHelper::Error($e->getMessage());
        }
    }

    /**
     * 移除 首页  推荐  专题
     * @param $res_id
     * @param $br_id
     */
    public function RemoveThird($res_id, $br_id)
    {

        if ($br_id) {
            $where = ['res_id' => $res_id, 'br_id' => $br_id];
        } else {
            $where = ['res_id' => $res_id];
        }
        $num1 = HySupport::deleteAll($where);
        $num2 = HySpecialResource::deleteAll($where);
        Yii::info('移除首页 推荐资源' . $num1 . '个，移除专题资源' . $num2 . '个', 'my');
    }

    /**
     * @param $id
     * @param $r_type
     * @param $branchId
     * @throws \yii\base\ExitException
     */
    public function CheckSelf($id, $r_type, $branchId)
    {

        $model = (new ResourceLogic())->getResourceModel($r_type);
        $res = $model->find()
            ->select('res_id')
            ->where(['id' => $id])
            ->andWhere(['is_self' => $branchId])
            ->count();

        if (empty($res))
            BaseHelper::Error('没有可操作的资源');
        if ($res != count($id)) {
            BaseHelper::Error('不能操作的系统分配资源');
        }
    }

}